<template>
  <a-card>
    <!-- <a-spin :spinning="spinning" size="large"> -->
    <a-form @submit="handleSubmit" :form="form" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
      <a-form-item label="频道名称" has-feedback>
        <a-input
          v-decorator="[
            'name',
            {
              rules: [
                {
                  required: true,
                  max: 6,
                  message: '请输入频道名称，不超过6个字符,不可输入符号！',
                  whitespace: true,
                  pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/
                }
              ]
            }
          ]"
          name="name"
          placeholder="建议名称为4个字，最多可输入6个字"
          :max-length="6"
          autocomplete="off"
        />
      </a-form-item>
      <a-form-item label="上下线时间" has-feedback>
        <a-range-picker
          style="width: 100%"
          :show-time="{ format: 'HH:mm:ss' }"
          format="YYYY-MM-DD HH:mm:ss"
          :placeholder="['Start Time', 'End Time']"
          v-decorator="['timePicker', { rules: [{ required: true, message: '请选择时间！' }] }]"
          @change="onChange"
          @ok="onOk"
        />
      </a-form-item>
      <a-form-item label="排序值" has-feedback>
        <a-input
          v-decorator="['priority', { rules: [{ required: true, pattern: /^[1-9]\d*$/, message: '请输入排序值，数字越小越靠前！', whitespace: true }] }]"
          name="name"
          placeholder="频道在首页的排序，填写数字，数字越小越靠前"
          autocomplete="off"
        />
      </a-form-item>
      <a-form-item label="频道内容规则" has-feedback required :wrapperCol="{ span: 24 }">
        <a-row>
          <!-- <a-col class="select-label">
              <a-form-item style="width:100%" label="搭配性别" has-feedback :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
                <a-select
                  v-model="mdl.genders"
                  placeholder="请选择"
                  :getPopupContainer="triggerNode => triggerNode.parentNode"
                  mode="multiple"
                  :allowClear="true"
                  @change="
                    e => {
                      handleSelectChange(e, 'genders')
                    }
                  "
                >
                  <a-select-option :value="'all'">全部</a-select-option>
                  <a-select-option :value="value.code" v-for="(value, index) in gendersList" :key="index">
                    {{ value.desc }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
          <a-col class="select-label">
            <a-form-item style="width: 100%" label="适用品牌" has-feedback :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
              <a-select
                v-model="mdl.brands"
                placeholder="请选择"
                :getPopupContainer="triggerNode => triggerNode.parentNode"
                mode="multiple"
                :allowClear="true"
                @change="
                  e => {
                    handleSelectChange(e, 'brands')
                  }
                "
              >
                <a-select-option :value="'all'">全部</a-select-option>
                <a-select-option :value="value.name" v-for="value in brandsList" :key="value.name">
                  {{ value.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col class="select-label">
            <a-form-item style="width: 100%" label="搭配师" has-feedback :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
              <a-select
                v-model="mdl.fashioners"
                placeholder="请选择"
                :getPopupContainer="triggerNode => triggerNode.parentNode"
                mode="multiple"
                :allowClear="true"
                @change="
                  e => {
                    handleSelectChange(e, 'fashioners')
                  }
                "
              >
                <a-select-option :value="'all'">全部</a-select-option>
                <a-select-option :value="value.id" v-for="value in fashionersList" :key="value.id">
                  {{ value.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col class="select-label">
            <a-form-item style="width: 100%" label="年份" has-feedback :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
              <a-select
                v-model="mdl.years"
                placeholder="请选择"
                mode="tags"
                :allowClear="true"
                @change="
                  e => {
                    handleSelectChange(e, 'years')
                  }
                "
              >
                <a-select-option :value="'all'">全部</a-select-option>
                <a-select-option :value="item.name" v-for="(item, index) in yearList" :key="index"> {{ item.name }} </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col class="select-label">
            <a-form-item style="width: 100%" label="季节" has-feedback :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
              <a-select
                v-model="mdl.seasons"
                placeholder="请选择"
                :allowClear="true"
                mode="tags"
                @change="
                  e => {
                    handleSelectChange(e, 'seasons')
                  }
                "
              >
                <a-select-option :value="'all'">全部</a-select-option>
                <a-select-option :value="item.code" v-for="(item, index) in season" :key="index"> {{ item.name }} </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <!-- 循环 -->
          <a-col class="select-label" v-for="(item, index) in tagGroups" :key="index">
            <a-form-item style="width: 100%" :label="item.title" has-feedback :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
              <a-select
                v-model="item.checkedList"
                placeholder="请选择"
                :getPopupContainer="triggerNode => triggerNode.parentNode"
                mode="tags"
                :allowClear="true"
                @change="
                  e => {
                    handleSelectChange(e, 'tags', index)
                  }
                "
              >
                <a-select-option :value="'all'">全部</a-select-option>
                <a-select-option :value="value.code" v-for="value in item.children" :key="value.code">
                  {{ value.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col class="select-label">
            <a-form-item style="width: 100%" label="其他标签" has-feedback :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
              <a-select
                placeholder="请选择"
                mode="tags"
                @change="
                  e => {
                    handleSelectChange(e, 'seasons')
                  }
                "
              >
                <!-- <a-select-option :value="'all'">全部</a-select-option> -->
              </a-select>
            </a-form-item>
          </a-col>
          <a-col>
            <div class="ant-col ant-col-sm-7 ant-col-lg-5"></div>
            <div class="ant-col ant-col-sm-17 ant-col-lg-10 ant-form-item-control has-feedback has-error" v-show="channelRules">
              <div class="ant-form-explain">请至少选择一个频道内容规则！</div>
            </div>
          </a-col>
        </a-row>
      </a-form-item>
      <a-form-item label="频道内容排序方式">
        <a-radio-group v-decorator="['sortType', { rules: [{ required: true }] }]">
          <a-radio :value="0"> 最新（创建时间倒序） </a-radio>
          <a-radio :value="1"> 最热(BOX内销量从大到小) </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="置顶搭配ID">
        <a-input
          v-decorator="['tops', { rules: [{ whitespace: true, message: '请输入行动点！' }], initialValue: '' }]"
          name="name"
          placeholder="多个ID用英文逗号,隔开，前端按照置顶ID顺序展示"
          autocomplete="off"
        />
      </a-form-item>
      <a-form-item label="图标">
        <a-upload
          v-decorator="['upload']"
          name="file"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="true"
          :multiple="false"
          action="https://up-z0.qiniup.com/"
          :before-upload="beforeUpload"
          :data="formBasePicData"
          :headers="headers"
          @change="handleChange"
          :fileList="singleFileList"
        >
          <div>
            <a-icon type="plus" />
            <div class="ant-upload-text">Upload</div>
          </div>
          <a-input v-decorator="['img', { initialValue: '' }]" type="hidden" />
        </a-upload>
      </a-form-item>
      <a-divider />

      <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <div style="display: flex; justify-content: center">
          <a-button htmlType="submit" type="primary">提交</a-button>
          <a-button style="margin-left: 8px" @click="handleBack">关闭</a-button>
        </div>
      </a-form-item>
    </a-form>
    <!-- </a-spin> -->
  </a-card>
</template>
<script>
import moment from 'moment'
import 'moment/locale/zh-cn'
import { uploadToken } from '@/api/api'
import { channelDetail, channelCreate } from '@/api/box/marketing'
import { uploadImgHost } from '@/assets/js/common'
import { querySysCateTree } from '@api/box/api'
import { getSizeNos } from '@/api/box/boxLook'
import setItem$ from 'dingtalk-jsapi/api/util/domainStorage/setItem'

export default {
  name: 'BaseForm',
  data() {
    return {
      moment,
      // spinning: false,
      channelId: '',
      uploadToken: '',
      form: this.$form.createForm(this),
      beginDate: '',
      endDate: '',
      // loading: false,
      imageUrl: '',
      formBasePicData: {
        token: '',
        key: ''
      },
      headers: {
        authorization: 'authorization-text'
      },
      imgBaseUrl: '',
      singleFileList: [],
      season: [],
      yearList: [],
      brandsList: [],
      fashionersList: [],
      gendersList: [],
      brandTags: [],
      seasonTags: [],
      styleTags: [],
      mdl: {
        brands: [],
        genders: [],
        fashioners: [],
        tags: [],
        years: [],
        seasons: []
      },
      tagGroups: [],
      channelRules: false,
      codeUrl: ''
    }
  },
  created() {
    this.imgBaseUrl = uploadImgHost
    this.getSysCateTree()
    this.getSize()
  },
  activated() {
    this.fetchPathId()
  },
  deactivated() {
    this.form.resetFields()
    this.channelId = ''
    this.beginDate = ''
    this.endDate = ''
    this.imageUrl = ''
    this.imgBaseUrl = ''
    this.singleFileList = []
    this.brandsList = []
    this.fashionersList = []
    this.gendersList = []
    this.brandTags = []
    this.seasonTags = []
    this.styleTags = []
    this.mdl = {
      brands: [],
      genders: [],
      fashioners: [],
      tags: [],
      years: [],
      seasons: []
    }
    this.tagGroups = []
  },
  methods: {
    getSize() {
      getSizeNos().then(res => {
        if (res.code === 0) {
          console.log(res, 'res')
          this.season = res.data[3].children
          this.yearList = res.data[2].children
        } else {
          this.$message.error()
        }
      })
    },
    // 标签
    getSysCateTree() {
      querySysCateTree('B08')
        .then(res => {
          const { code, result, message } = res
          if (code == 0) {
            // console.log(result, 'data')
            let data = JSON.parse(JSON.stringify(result))
            data.splice(1, 1)
            console.log(data, 'data')
            const tagGroups = data.map(item => {
              const checkedList = []
              return {
                ...item,
                checkedList
              }
            })
            this.tagGroups = tagGroups
          } else {
            this.$message.error(message)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    fetchPathId() {
      this.fetchUploadToken()
      const id = this.$route.params.id
      this.productId = this.$route.params.id
      if (id !== 'add') {
        this.channelId = id
        this.fetchData(id)
      } else {
        this.singleFileList = []
        this.fetchData('null')
      }
    },
    fetchUploadToken() {
      uploadToken()
        .then(res => {
          if (res.code === 0) {
            this.uploadToken = res.data
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('fetchUploadToken:' + err)
        })
    },
    async fetchData(d) {
      // this.spinning = true
      let tagGroup = await this.querySys()
      let yearArr = await this.getNo()
      this.form.getFieldDecorator('sortType')
      this.form.setFieldsValue({
        sortType: 0
      })
      channelDetail(d)
        .then(res => {
          // console.log(res)
          if (res.code === 0) {
            this.brandsList = res.data.brands
            this.fashionersList = res.data.fashioners
            // this.gendersList = res.data.genders

            this.tagGroups = tagGroup
            this.yearList = yearArr

            if (res.data.optionalChannel !== null && this.channelId !== '') {
              const optionalChannel = res.data.optionalChannel
              this.codeUrl = optionalChannel.codeUrl
              const passTime = [moment(optionalChannel.beginDate), moment(optionalChannel.endDate)]
              this.beginDate = passTime[0].format('YYYY-MM-DD HH:mm:ss')
              this.endDate = passTime[1].format('YYYY-MM-DD HH:mm:ss')
              if (optionalChannel.img !== null) {
                this.singleFileList.push({
                  url: optionalChannel.img,
                  uid: optionalChannel.img,
                  name: optionalChannel.img,
                  status: 'done'
                })
                this.form.setFieldsValue({
                  img: optionalChannel.img,
                  upload: this.singleFileList
                })
              }
              this.form.setFieldsValue({
                name: optionalChannel.name,
                tops: optionalChannel.tops,
                priority: optionalChannel.priority,
                sortType: optionalChannel.sortType,
                timePicker: passTime
              })
              if (optionalChannel.brand !== null) {
                const brand = optionalChannel.brand.split(',')
                this.mdl.brands = brand
              }
              if (optionalChannel.fashioner !== null) {
                const fashioner = optionalChannel.fashioner.split(',')
                this.mdl.fashioners = fashioner
              }
              if (optionalChannel.years !== null) {
                let yearName = optionalChannel.years.split(',')
                let yearInfo = []
                let yearArr = []
                let yearOther = []

                this.yearList.forEach(item => {
                  yearName.forEach(info => {
                    if (item.name == info) {
                      yearInfo.push(item)
                    }
                    if (info == '0000') {
                      yearArr = this.yearList.filter(item => item.code == '0000')
                    }
                    if (item.name != info) {
                      yearOther = this.yearList.filter(item => item.name == '其他年份')
                    }
                  })
                })

                yearInfo = [...yearInfo, ...yearArr, ...yearOther]
                let newArr = yearInfo.map(item => item.name)
                this.mdl.years = newArr
              }
              if (optionalChannel.seasons !== null) {
                this.mdl.seasons = optionalChannel.seasons.split(',')
              }
              if (optionalChannel.tags !== null) {
                const tags = optionalChannel.tags.split(',')

                var key
                for (var i = 0; i < this.tagGroups.length; i++) {
                  this.tagGroups[i].checkedList = tags.filter(value => {
                    console.log(value, 'value')
                    for (key in this.tagGroups[i].children) {
                      if (this.tagGroups[i].children[key].code === value) {
                        return value
                      }
                    }
                  })
                }
              }
            } else {
              this.mdl = {
                brands: [],
                genders: [],
                fashioners: [],
                tags: []
              }
              this.form.setFieldsValue({
                sortType: 0,
                img: '',
                upload: [],
                name: '',
                tops: '',
                priority: '',
                sortType: '',
                timePicker: []
              })
            }
          } else {
            this.$message.warning(res.msg)
          }
          // this.spinning = false
        })
        .catch(err => {
          console.log(err)
        })
    },
    querySys() {
      return querySysCateTree('B08').then(res => {
        const { code, result, message } = res
        if (code == 0) {
          // console.log(result, 'data')
          let data = JSON.parse(JSON.stringify(result))
          data.splice(1, 1)
          console.log(data, 'data')
          const tagGroups = data.map(item => {
            const checkedList = []
            return {
              ...item,
              checkedList
            }
          })
          return tagGroups
        } else {
          return []
        }
      })
    },
    getNo() {
      return getSizeNos().then(res => {
        if (res.code === 0) {
          console.log(res, 'res')

          return res.data[2].children
        } else {
          return []
        }
      })
    },
    onChange(value, dateString) {
      console.log('Selected Time: ', value)
      console.log('Formatted Selected Time: ', dateString)
      this.form.getFieldDecorator('time')
      this.form.setFieldsValue({
        time: dateString
      })
    },
    onOk(value) {
      console.log('onOk: ', value)
      this.beginDate = value[0].format('YYYY-MM-DD HH:mm:ss')
      this.endDate = value[1].format('YYYY-MM-DD HH:mm:ss')
      console.log('startTime', this.beginDate)
      console.log('endTime', this.endDate)
    },
    handleSelectChange(value, type, index) {
      console.log(value)
      // console.log(type, index)
      switch (type) {
        case 'brands':
          if (value.indexOf('all') !== -1) {
            this.mdl.brands = this.getAll(this.brandsList, 'brands')
          }
          break
        case 'genders':
          if (value.indexOf('all') !== -1) {
            this.mdl.genders = this.getAll(this.gendersList, 'genders')
          }
          break
        case 'fashioners':
          if (value.indexOf('all') !== -1) {
            this.mdl.fashioners = this.getAll(this.fashionersList)
          }
          break
        case 'years':
          if (value.indexOf('all') !== -1) {
            this.mdl.years = this.getAll(this.yearList, 'years')
          }
          break
        case 'seasons':
          if (value.indexOf('all') !== -1) {
            this.mdl.seasons = this.getAll(this.season, 'seasons')
          }
          break
        case 'tags':
          if (value.indexOf('all') !== -1) {
            console.log(this.tagGroups)
            this.tagGroups[index].checkedList = this.getAll(this.tagGroups[index].children, 'tags')
          }
          break
      }
    },
    getAll(list, type) {
      if (type === 'brands') {
        const brands = list.map(item => item.name)
        return brands
      } else if (type === 'genders') {
        const genders = list.map(item => item.code)
        return genders
      } else if (type === 'tags') {
        const tags = list.map(item => item.code)
        return tags
      } else if (type === 'seasons') {
        const seasons = list.map(item => item.code)
        return seasons
      } else if (type === 'years') {
        const years = list.map(item => item.name)
        return years
      } else {
        const all = list.map(item => item.id)
        return all
      }
    },
    handleChange(info) {
      if (info.fileList.length > 0) {
        const uploadList = [info.fileList[info.fileList.length - 1]]
        console.log(uploadList)
        const fileList = uploadList.map(file => {
          console.log(file)
          if (file.response) {
            // console.log(info)
            file.url = this.imgBaseUrl + file.response.key
            console.log('上传成功', file.response)
          }
          return file
        })
        this.singleFileList = fileList
        console.log(this.singleFileList)
        this.form.setFieldsValue({ img: fileList[0].url })
      } else {
        this.singleFileList = []
        this.form.setFieldsValue({ img: '' })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      if (isLt2M && isJpgOrPng) {
        const key = new Date().getTime() + '-' + file.name
        this.formBasePicData.key = key
        this.formBasePicData.token = this.uploadToken
        return isJpgOrPng && isLt2M
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        // console.log(err)
        if (!err) {
          console.log(this.mdl)
          let yearInfo = []
          let newArr = []
          if (this.mdl.years && this.mdl.years.length > 0) {
            this.mdl.years.forEach(ele => {
              this.yearList.forEach(item => {
                if (ele == item.name) {
                  yearInfo.push(item)
                }
              })
            })
            console.log(yearInfo, 'yearInfo')

            for (let child of yearInfo) {
              if (child.name == '其他年份') {
                let arr = child.code.map(e => e.code)
                newArr = [...newArr, ...arr]
              } else {
                newArr.push(child.code)
              }
            }
          }
          console.log(newArr, 'newArr') // 年份
          // return
          for (var a = 0; a < this.tagGroups.length; a++) {
            this.mdl.tags = this.mdl.tags.concat(this.tagGroups[a].checkedList)
          }
          console.log(this.mdl.seasons)
          if (this.mdl.brands.length === 0 && this.mdl.genders.length === 0 && this.mdl.fashioners.length === 0 && this.mdl.tags.length === 0 && !this.mdl.seasons && !this.mdl.years) {
            this.channelRules = true
            return false
          } else {
            this.channelRules = false
            const data = values
            delete data.upload
            if (this.mdl.brands.length > 0) {
              data.brand = this.mdl.brands.toString()
            } else {
              data.brand = ''
            }
            if (this.mdl.fashioners.length > 0) {
              data.fashioner = this.mdl.fashioners.toString()
            } else {
              data.fashioner = ''
            }
            data.years = this.mdl.years && this.mdl.years.length > 0 ? newArr.toString() : ''
            data.seasons = this.mdl.seasons && this.mdl.seasons.length > 0 ? this.mdl.seasons.toString() : ''
            if (this.mdl.genders.length > 0) {
              data.gender = this.mdl.genders.toString()
            } else {
              data.gender = ''
            }
            console.log(this.mdl.tags, 'this.mdl.tags')
            if (this.mdl.tags.length > 0) {
              data.tags = this.mdl.tags.toString()
            } else {
              data.tags = ''
            }
            if (this.channelId !== '') {
              data.id = this.channelId
            }
            delete data.timePicker
            data.beginDate = this.beginDate
            data.endDate = this.endDate
            console.log(data)
            // this.spinning = true
            this.submitCreate(data)
          }
        }
      })
    },
    submitCreate(d) {
      console.log(d)

      // return
      const data = {
        requestData: d
      }
      channelCreate(data)
        .then(res => {
          console.log(res)
          if (res.code === 0) {
            this.$message.success('成功！')
            // const id = this.$route.params.id
            // if (id === 'add') {
            //   this.channelId = res.data.data.id
            //   this.codeUrl = res.data.data.codeUrl
            // }
            setTimeout(() => {
              // this.spinning = false
              this.form.resetFields()
              this.$router.push('/box/operations/channel/list')
            }, 2000)
          } else {
            // this.spinning = false
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('submitCreate:' + err)
        })
    },
    handleBack() {
      this.form.resetFields()
      this.$router.go(-1)
    }
  }
}
</script>
<style scoped>
.icon-img {
  width: 86px;
  height: 86px;
  object-fit: scale-down;
}
.select-label {
  display: flex;
}
.codeimg {
  margin: 0 auto;
  display: block;
  width: 120px;
  height: 120px;
}
</style>

